from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.contrib.auth import get_user_model
from utils.JWTTool import jwtTool

# 请确保此文件不包含任何 channels、BaseMiddleware、WebSocket 相关的导入和代码，仅保留 REST 认证相关内容。

User = get_user_model()

class CustomJWTAuthentication(BaseAuthentication):
    def authenticate(self, request):
        auth = request.headers.get('Authorization', '')
        if not auth or not auth.startswith('Bearer '):
            return None  # 不处理无token的请求
        token = auth.split(' ')[1]
        try:
            payload = jwtTool.decode_token(token)
            user_id = payload.get('user_id')
            if not user_id:
                raise AuthenticationFailed('Token中没有user_id')
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                raise AuthenticationFailed('用户不存在')
            return (user, token)
        except Exception as e:
            raise AuthenticationFailed(str(e))